package cookie;

import utils.CookieUtils;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * 修改cookie
 */
public class C4_UpdateCookie extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        //1.根据name查找cookie
        String cookieName = "email";
        Cookie[] cookies = req.getCookies();
        Cookie cookie = CookieUtils.readCookieByName(cookieName, cookies);

        //2.在服务器端修改指定cookie值
        if (null == cookie) {
            //在当前浏览器没有找到
            System.out.println("当前访问服务端的浏览器没有该cookie");
        } else {
            cookie.setValue("lmy-hi");
        }

        //3.回送给浏览器保存
        resp.setContentType("text/html;charset=utf-8");
        if (cookie != null) {
            //创建同名cookie相当于覆盖原来的cookie，也就是实现了cookie的修改
            resp.addCookie(cookie);
        }
        PrintWriter writer = resp.getWriter();
        writer.print("<h1>修改cookie成功</h1>");
        writer.flush();
        writer.close();
    }
}
